package com.rayo.accesscontrollercopy.module.main;

import android.Manifest;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AlertDialog;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextClock;

import com.github.ybq.android.spinkit.SpinKitView;
import com.github.ybq.android.spinkit.style.Wave;
import com.litesuits.common.utils.HexUtil;
import com.rayo.accesscontrollercopy.R;
import com.rayo.accesscontrollercopy.app.BaseActivity;
import com.rayo.accesscontrollercopy.config.GlobalVariables;
import com.rayo.accesscontrollercopy.model.db.bean.CurrentUserData;
import com.rayo.accesscontrollercopy.model.db.bean.KeyBoxData;
import com.rayo.accesscontrollercopy.model.db.bean.KeyData;
import com.rayo.accesscontrollercopy.model.db.bean.SiteData;
import com.rayo.accesscontrollercopy.model.db.bean.Status;
import com.rayo.accesscontrollercopy.model.db.dao.CurrentUserDao;
import com.rayo.accesscontrollercopy.model.db.dao.CurrentUserImpl;
import com.rayo.accesscontrollercopy.model.db.dao.KeyBoxDao;
import com.rayo.accesscontrollercopy.model.db.dao.KeyBoxImpl;
import com.rayo.accesscontrollercopy.model.db.dao.KeyDataDao;
import com.rayo.accesscontrollercopy.model.db.dao.KeyDataImp;
import com.rayo.accesscontrollercopy.model.db.dao.SiteDao;
import com.rayo.accesscontrollercopy.model.db.dao.SiteImpl;
import com.rayo.accesscontrollercopy.model.network.WebSocketHelp;
import com.rayo.accesscontrollercopy.module.login.LoginActivity;
import com.rayo.accesscontrollercopy.module.setting.SettingActivity;
import com.rayo.accesscontrollercopy.utils.BroadcastUtils;
import com.rayo.accesscontrollercopy.utils.CancelUtils;
import com.rayo.accesscontrollercopy.utils.ToastUtils;
import com.rayo.keyholder.data.KeyHolderCmd;
import com.rayo.keyholder.data.KeyHolderData;
import com.rayo.keyholder.serialport.KeyHolderService;
import com.rayo.wallreader.utils.TimeUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by yanghaojie on 16/7/27.
 */
public class MainActivity extends BaseActivity implements IMainView {

    private View mView;
    private Dialog mDialog, mDialog1, mDialog2;
    private Dialog mTagDialog;
    private Button mButton;
    private SpinKitView mSpinKitView;
    private MainPresenter presenter;

    private MainFragment mMainFragment;
    private CollectFragment mCollectFragment;
    private OpenFragment mOpenFragment;

    private ImageView mIvActivityMainButtonstatus;

    private ImageView mIvActivityMainBoxstatus;

    private ImageView mIvActivityMainNetwork;

    private ImageView mIvActivityMainHome;

    private TextClock mTvActivityMainNowtime;



    private LinearLayout llView;

    public static KeyHolderService mKeyHolderService;
    private boolean door = false;
    //    private boolean illegal = false;
    private String tagId;
    private int oldCount = 0;
    public static int OldCount = 0;
    private FragmentManager mFragmentManager;
    private Subscription sercuritySp, mSubscription;
    private KeyDataDao mKeyDataDao = new KeyDataImp();
    public static Status mStatus = new Status();
    private boolean bindService = false;

    public static final int DOOR_OPEN = 0;
    public static final int DOOR_CLOSE = 1;
    public static int DOOR_STATUS;
    public static int KEY;
    public static byte KEYBOX;

    private int readTagCount = 0;
    private int readTagCurrent = 0;
    private HashMap<Integer, String> errors = new HashMap<>();
    private HashMap<Integer, String> nextErrors = new HashMap<>();
    private StringBuilder sb = new StringBuilder("");
    public static boolean open = false;
    private String oldException = "11";
    public static final String SERVICE = "com.rayo.keyholder.main";
    public static final String STATUS = "com.rayo.keyholder.status";
    public static final int STOP = 1;
    public static final int START = 0;
    private boolean relese = false;
    private boolean checkTag = false;
    private Handler mHandler = new Handler();


    public static boolean collect = false;
    public static boolean main = false;
    private int tagCount = -1;
    private boolean countTag = false;
    private byte address;
    public static final String UPDATA = "updata";
    private List<Byte> keyBox = new ArrayList<Byte>();
    private boolean isMainTheard = false;

    private KeyData mKeyData;
    private IHardware mHardware = new IHardware() {
        @Override
        public void DoorState(int flag) {
            if (flag == 0) {
                door = true;
//                illegal = true;
                mIvActivityMainBoxstatus.setBackgroundResource(R.color.blue1);
            } else {
                door = false;
//                illegal = false;
                mIvActivityMainBoxstatus.setBackgroundResource(R.color.Green);
            }
        }

        @Override
        public void KeyState(int pos) {
        }
    };
    private BroadcastReceiver mKeyHolderReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            StringBuilder stringBuilder = new StringBuilder(64);
            final String action = intent.getAction();
            if (intent.getSerializableExtra(KeyHolderService.EXTRA_DATA) instanceof Integer) {
                return;
            }
            if (isMainTheard) {
                return;
            }
            final KeyHolderData keyHolderData = (KeyHolderData) intent.getSerializableExtra(KeyHolderService.EXTRA_DATA);
            switch (action) {
                case KeyHolderService.ACTION_DATA_WRITE:
                    stringBuilder.append("MainSend:");
                    stringBuilder.append(HexUtil.encodeHexStr(keyHolderData.getData()));
                    Log.e("write", stringBuilder.toString());
                    break;
                case KeyHolderService.ACTION_DATA_READ:
                    stringBuilder.append("MainRead:");
                    stringBuilder.append(String.format("%02X", keyHolderData.getCmd()) + "-");
                    stringBuilder.append(HexUtil.encodeHexStr(keyHolderData.getData()));

                    Log.e("read", stringBuilder.toString());
                    break;
                case KeyHolderService.ACTION_CLOSE:
                    break;

                case UPDATA:

                    updata();
                    break;
                default:
                    break;
            }
        }
    };



    private void updata() {

        KeyBoxDao keyBoxDao = new KeyBoxImpl();
        List<KeyBoxData> keyBoxDataList = keyBoxDao.findAll();

        keyBox.clear();
        for (int i = 0; i < keyBoxDataList.size(); i++) {
            if (keyBoxDataList.get(i).isIsopen()) {
                keyBox.add((byte) (i + 1));
            }
        }
        BroadcastUtils.send(MainActivity.this, START);
    }

    private ServiceConnection mKeyHolderConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            bindService = true;
            mKeyHolderService = ((KeyHolderService.LocalBinder) service).getService();
            BroadcastUtils.send(MainActivity.this, START);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mKeyHolderService = null;
            bindService = false;

        }

    };

    private int i = 0;
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void onReceive(Context context, Intent intent) {
            int action = intent.getIntExtra("flag", -1);
            if (action == START) {
                isMainTheard = false;
                CancelUtils.unsubscribe(mSubscription);
                final List<KeyData> mKeyDataList = new KeyDataImp().getAllKey();

            } else if (action == STOP) {
                isMainTheard = true;
                CancelUtils.unsubscribe(mSubscription);
            }
        }
    };
    private MainFragment.ISwitchFra mISwicthFra = new MainFragment.ISwitchFra() {
        @Override
        public void swicth() {
//            if (MainActivity.mStatus.getKeycount() != 4) {
            mCollectFragment = new CollectFragment();
            mCollectFragment.setmIHardware(mHardware);
            getSupportFragmentManager().beginTransaction().replace(R.id.fl_activity_main, mCollectFragment).addToBackStack(null).commit();
//            } else {
//                ToastUtils.showShortToast(MainActivity.this, getString(R.string.key_count_is_max));
//            }
        }
    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void setupViews() {
        mIvActivityMainBoxstatus = (ImageView) findViewById(R.id.iv_activity_main_boxstatus);
        mIvActivityMainButtonstatus = (ImageView) findViewById(R.id.iv_activity_main_buttonstatus);
        mIvActivityMainNetwork = (ImageView) findViewById(R.id.iv_activity_main_network);
//        mIvActivityMainHome = findViewById(R.id.iv_activity_main_home);
        mTvActivityMainNowtime = (TextClock) findViewById(R.id.tv_activity_main_nowtime);
        llView = findViewById(R.id.llView);
//        mIvActivityMainHome.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent = new Intent(getContext(), LoginActivity.class);
//                intent.putExtra(LoginActivity.EXTRA_DATA, LoginActivity.SETTING);
//                startActivity(intent);
//            }
//        });
    }

    private IntentFilter intentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(SERVICE);
        return intentFilter;
    }

    private IntentFilter makeUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(KeyHolderService.ACTION_DATA_READ);
        intentFilter.addAction(KeyHolderService.ACTION_DATA_WRITE);
        intentFilter.addAction(KeyHolderService.ACTION_CLOSE);
        intentFilter.addAction(UPDATA);
        return intentFilter;
    }

    @Override
    protected void initialized() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        String imei = ((TelephonyManager) getSystemService(TELEPHONY_SERVICE)).getDeviceId();
        presenter = new MainPresenter(getContext(), this);
        presenter.initData();
        mFragmentManager = getSupportFragmentManager();
        mMainFragment = new MainFragment();
        mFragmentManager.beginTransaction().replace(R.id.fl_activity_main, mMainFragment).commit();
        mMainFragment.setmISwicthFra(mISwicthFra);
//        isShowInfo(false);
        updata();
        if (presenter.isNewSystem()) {
            startActivity(new Intent(this, SettingActivity.class));
        }
        Intent service = new Intent(this, KeyHolderService.class);
        bindService(service, mKeyHolderConnection, Context.BIND_AUTO_CREATE);
        registerReceiver(mKeyHolderReceiver, makeUpdateIntentFilter());
        registerReceiver(mReceiver, intentFilter());

        SiteDao siteDao = new SiteImpl();
        List<SiteData> list = siteDao.findAll();
        Log.d("list",list.size()+"");

    }

    @Override
    protected void onResume() {
        super.onResume();
        setDateFormat(GlobalVariables.getInstance().getmSystemData().getDateFormat());


    }

    @Override
    protected void onStop() {
        super.onStop();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.onDestroy();
        unregisterReceiver(mKeyHolderReceiver);
        unregisterReceiver(mReceiver);
        try {
            if (mKeyHolderConnection != null)
                unbindService(mKeyHolderConnection);
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("exx", e.toString());

        } finally {
            if (mDialog != null) {
                mDialog.dismiss();
            }
            if (mTagDialog != null) {
                mTagDialog.dismiss();
            }
            if (mDialog2 != null) {
                mDialog2.dismiss();
            }
            if (mDialog1 != null) {
                mDialog1.dismiss();
            }
            mHandler.removeCallbacksAndMessages(null);
            WebSocketHelp.getmInstance().closeWebsocket(true);
            CancelUtils.unsubscribe(mSubscription);
        }

    }

    @Override
    public void onClick(View v) {
//        switch (v.getId()) {
//            case R.id.btn_open_controller:
//                isShowInfo(false);
//                presenter.open();
//                open(false);
//                presenter.onTouch();
//                break;
//            case R.id.btn_close:
//                isShowInfo(false);
//                open(false);
//                presenter.onTouch();
//                break;
//            default:
//                break;
//        }
    }

    //
    @Override
    public void showProgressBar(boolean isShow) {

    }

    @Override
    public void showSnackBar(String txt) {
//        showShortSnackbar(mRlMain, txt, null);
    }

    @Override
    public void showAlertDialog(String txt) {
        if (null != txt)
            new AlertDialog.Builder(getContext()).setTitle(R.string.app_name).setMessage(txt)
                    .setIcon(R.mipmap.ic_launcher).setPositiveButton(R.string.okay, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }).show();
    }

    @Override
    public void setDateFormat(int format) {
        String[] formats = getResources().getStringArray(R.array.data_format);
        if (null != formats && formats.length > format) {
            mTvActivityMainNowtime.setFormat12Hour(formats[format]);
            mTvActivityMainNowtime.setFormat24Hour(formats[format]);
        }
    }

    @Override
    public void setNetWork(boolean isOnline) {
        mIvActivityMainNetwork.setVisibility(View.VISIBLE);
        if (isOnline) {
            mIvActivityMainNetwork.setBackgroundResource(R.color.blue1);
        } else {
            mIvActivityMainNetwork.setBackgroundResource(R.color.SecondText);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(KEY==1){
            mOpenFragment.onKeyDown();
            return false;
        }
        if (mMainFragment != null && mMainFragment.getKeyDown()) {

            Intent intent = null;
            switch (keyCode) {
                case KeyEvent.KEYCODE_BACK:

                    intent = new Intent(getContext(), LoginActivity.class);
                    intent.putExtra(LoginActivity.EXTRA_DATA, LoginActivity.FINISH);
                    startActivity(intent);
                    break;
                case KeyEvent.KEYCODE_HOME:
                    intent = new Intent(getContext(), LoginActivity.class);
                    intent.putExtra(LoginActivity.EXTRA_DATA, LoginActivity.FINISH);
                    startActivity(intent);
                    break;
                case KeyEvent.KEYCODE_MENU:
                    intent = new Intent(getContext(), LoginActivity.class);
                    intent.putExtra(LoginActivity.EXTRA_DATA, LoginActivity.SETTING);
                    startActivity(intent);
                    break;
                default:
                    break;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        final String keyId = intent.getStringExtra("keyid");


        if (!TextUtils.isEmpty(keyId)) {
            mOpenFragment = new OpenFragment();
            mOpenFragment.setHardware(mHardware);
            Bundle bundle = new Bundle();
            bundle.putString("keyid", keyId);
            mOpenFragment.setArguments(bundle);
            mFragmentManager.beginTransaction().replace(R.id.fl_activity_main, mOpenFragment).addToBackStack(null).commit();
        }
    }





}
